package com.lovo.action;

import com.google.gson.Gson;
import com.lovo.bean.Book;
import com.lovo.service.IBookService;
import com.lovo.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "BookServlet",urlPatterns = "/book.do")
public class BookServlet extends HttpServlet {

    private IBookService ibs =new BookServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if(method==null||method.equals("")){

        }else if(method.equals("showBooksByTypeId")){
            showBooksByTypeId(request,response);
        }
    }
    protected void showBooksByTypeId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tId = request.getParameter("typeId");
        int typeId =0;
        if(tId!=null){
            typeId =Integer.parseInt(tId);
        }
        List<Book> books = ibs.getBooksByTypeId(typeId);
        String json = new Gson().toJson(books);
        System.out.println("json = " + json);
        response.getWriter().write(json);
    }
}
